package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.config.FileServerConfig;
import io.renren.constant.AppConstant;
import io.renren.entity.*;
import io.renren.po.User;
import io.renren.service.UserService;
import io.renren.util.DfsUtil;
import io.renren.vo.FileServerResponse;
import io.renren.vo.RespModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * 应用客户端用户注册与维护
 *
 * @author levitian
 */
@RestController
@RequestMapping("/auth/user")
@Api(tags = "用户服务")
public class UserServiceController extends AbstractController {

    @Autowired
    private UserService userservice;

    @Autowired
    private FileServerConfig fileServerConfig;

    /**
     * 注册一个用户 使用短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/reg", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加一个新用户，使用短信验证码", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<String> add(@RequestBody UserRegModel user) {
        return userservice.add(user);
    }

    /**
     * 注册一个用户 不使用短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/new", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "注册新用户不使用短信验证码", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<String> addNewUser(@RequestBody UserRegModel user) {
        return userservice.addNewUser(user);
    }

    /**
     * 检查一个用户是否已注册
     *
     * @return
     */
    @PostMapping(value = "/exist", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "检测用户是否存在", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<User> userExist(@RequestBody UserExistModel user) {
        return userservice.userExist(user);
    }

    /**
     * 重置密码
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/resetpassword", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "重置密码", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<String> updatePasswordByReset(@RequestBody UserRegModel user) {
        return userservice.updatePasswordByReset(user);
    }

    /**
     * 修改密码
     *
     * @return
     */
    @Login
    @PostMapping(value = "/changepassword/{applicationId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改密码", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<String> updatePasswordByChange(@RequestBody ChangePasswordModel cpwmodel, @PathVariable String applicationId) {
        return userservice.updatePasswordByChange(cpwmodel);
    }

    /**
     * 获得用户信息
     *
     * @return
     */
    @Login
    @GetMapping(value = "/info/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获得用户信息", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<UserInfo> getInfo(@PathVariable("applicationId") String applicationId, String authtoken, HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        return userservice.getInfo(username);
    }

    /**
     * 增加或更新用户信息
     *
     * @return
     */
    @Login
    @PostMapping(value = "/info/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "增加或更新用户信息", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<String> addOrUpdateInfo(
            @PathVariable("applicationId") String applicationId,
            UserInfoModel userInfoModel,
            String jwttoken) {
        return userservice.addOrUpdateInfo(applicationId, userInfoModel, jwttoken);
    }

    /**
     * 图标上传
     *
     * @return
     */
    @Login
    @PostMapping(value = "/icon/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "图标上传", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<HashMap<String, Object>> addIcon(@PathVariable("applicationId") String applicationId,
                                                      MultipartFile file, HttpServletRequest request) {
        if (StringUtils.isBlank(applicationId)) {
            RespModel<HashMap<String, Object>> resp = new RespModel<>("failed", "406", "PARAM IS MISS", null);
            return resp;
        }

        try {
            FileServerResponse fileServerResponse =
                    DfsUtil.uploadFileByBinary(
                            file.getOriginalFilename(),
                            file.getBytes(),
                            ContentType.create(file.getContentType()),
                            fileServerConfig.getImageUploadUrl());
            String url = fileServerResponse.getRealHttpUrl();
            // 上传后有两个http://的问题
            if (StringUtils.isNotBlank(url)) {
                while (url.contains("http://http://")) {
                    url = url.replace("http://http://", "http://");
                }
            }
            //DfsUtil.uploadFileByMultipartFile(file, fileServerConfig.getImageUploadUrl());
            return userservice.addIcon(((String) request.getAttribute("username")), url);
        } catch (IOException e) {
            e.printStackTrace();
            return new RespModel<>().getRespModelInstance(AppConstant.STATU_FAIL, e.getMessage(), null);
        }
    }

    /**
     * 图标上传
     *
     * @return
     */
    @Login
    @PutMapping(value = "/icon/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "图标上传", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<HashMap<String, Object>> addIconByPut(@PathVariable("applicationId") String applicationId,
                                                           String base64Image, HttpServletRequest request) {
        if (StringUtils.isBlank(applicationId)) {
            RespModel<HashMap<String, Object>> resp = new RespModel<>("failed", "406", "PARAM IS MISS", null);
            return resp;
        }
        System.out.println("====" + base64Image);
        String username = ((String) request.getAttribute("username"));
        String s = uploadBase64StrImage(base64Image, username + "-icon.png");
        if (s != null) {
            return userservice.addIcon(username, s);
        } else {
            return new RespModel<>().getRespModelInstance(AppConstant.STATU_FAIL, "保存图片失败", null);
        }
    }

    /**
     * @param tokenGeneratorInputModel
     * @return
     */
    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户登陆", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<TokenModel> login(@RequestBody TokenGeneratorInputModel tokenGeneratorInputModel) {
        return userservice.login(tokenGeneratorInputModel);
    }


    /**
     * 绑定微信
     *
     * @return
     */
    @Login
    @PostMapping(value = "/boundWechat/{applicationId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "绑定微信", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "data", value = "json格式的字符串:\n{\n" +
            "applicationId:\"99a22c16-bd87-498e-a2a8-c55bf02b0b9d\",\n" +
            "userName:\"15966621423\",\n" +
            "wxAvatar:\"\",\n" +
            "nickName:\"\",\n" +
            "wxOpenId:\"djkssjffdf\",\n" +
            "wxUnionId:\"duuedhskdjf\"\n" +
            "}")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<String> updateBoundWechat(String data, @PathVariable String applicationId) {
        return userservice.updateBoundWechat(data);
    }

    /**
     * 微信解绑
     *
     * @return
     */
    @Login
    @PostMapping(value = "/unBoundWechat/{applicationId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "微信解绑", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<String> updateUnBoundWechat(String data, @PathVariable String applicationId) {
        return userservice.updateBoundWechat(data);
    }

    /**
     * 获取绑定微信信息
     *
     * @return
     */
    @Login
    @PostMapping(value = "/getBoundInfo", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取绑定微信信息", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<User> getBoundInfo(@RequestParam("data") String data) {
        return userservice.getBoundInfo(data);
    }


    /**
     * 获取消息列表
     *
     * @return
     */
    @GetMapping(value = "/getMyMessage/{userid}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取我的消息", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getMyMessage(@PathVariable String userid) {
        if (StringUtils.isBlank(userid)) {
            return new RespModel<List<MessageEntity>>()
                    .getRespModelInstance(AppConstant.STATU_FAIL, "MISSING PARAMETERS.", null);
        }
        return new RespModel<List<MessageEntity>>()
                .getRespModelInstance(AppConstant.STATU_SUCCESS, null, userservice.getMyMessage(userid));
    }


    /**
     * 读消息,用户读取消息的时候，修改消息已读状态
     *
     * @return
     */
    @GetMapping(value = "/read/{messageId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "读我的消息", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel read(@PathVariable String messageId) {
        if (StringUtils.isBlank(messageId)) {
            return new RespModel()
                    .getRespModelInstance(AppConstant.STATU_FAIL, "MISSING PARAMETERS.",null);
        }
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, null, userservice.read(messageId));
    }

}
